<?php namespace Home\Controller;
use Common\Model\Goods_attr;
use Common\Model\Goods;
//购物车控制器
class CartController extends CommonController{
	//显示购物车
	public function index(){
		if(isset($_SESSION['nickuser'])){
			$goods=Cart::getAllData();
			View::with('goods',$goods);
			View::make();
		}else{
			View::error('请先登录，再查看购物车');
		}
	}
	//添加购物车
	public function add(){
		if(isset($_SESSION['nickuser'])){
			$arr=Q('post.arr');
			$str=substr($arr['options'], 0,strlen($arr['options'])-1);
			$str=str_replace('|', ',', $str);
			$goods_attrModel=new Goods_attr;
			$options=$goods_attrModel
					->join('type_attr','shop_type_attr_taid','=','taid')
					->where("gaid IN (".$str.") AND shop_goods_gid={$arr['gid']}")
					->get();
			foreach($options as $k=>$v){
				$options[$k]="{$v['taname']}:{$v['gavalue']}";
			}
			//图片
			$goodsModel=new Goods;
			$pic=$goodsModel->where("gid={$arr['gid']}")->pluck('pic');
			$data = [
	            'id'        =>$arr['gid'], // 商品 ID
	            'name'      =>$arr['name'],// 商品名称
	            'num'       =>$arr['num'], // 商品数量
	            'price'     =>$arr['price'], // 商品价格
	            'pic'		=>$pic,//商品列表图片
	            'options' => $options// 其他参数如价格、颜色、可以为数组或字符串
	            ];
	        Cart::add($data);
			$massage=[
				'massage'=>'添加购物车成功',
				'num'=>$_SESSION['cart']['total_rows']
			];
			echo json_encode($massage);
		}else{
			echo json_encode('添加购物车失败，请登录后再进行添加');
		}
		
	}
	//修改购物车
	public function newNum(){
		$update=Q('post.update');
	   	$data=array( 
    		'sid'=>$update['SID'],// 唯一 sid，添加购物车时自动生成 
    		'num'=>$update['num']
		); 
		Cart::update($data); 
		$data['total']=$_SESSION['cart']['goods'][$update['SID']]['total'];
		$data['all_total']=$_SESSION['cart']['total'];
		$data['total_rows']=$_SESSION['cart']['total_rows'];
		echo json_encode($data);
	}
	//删除购物车
	public function del(){
	    $del=Q('post.del');
		$data=array( 
    		'sid'=>$del['SID'],// 唯一 sid，添加购物车时自动生成 
    		'num'=>$del['num']
		); 
		Cart::update($data);
		$data['all_total']=$_SESSION['cart']['total'];
		$data['total_rows']=$_SESSION['cart']['total_rows'];
		
		echo json_encode($data);
	}
}
?>